let defaultToken = JSON.parse(Utils.GetSessionStorage('SNLoginUserInfo'));
import SwitchOrgAPI from '../../../../../public/js/common/api/switchorg/switchorg.api.js';

(function (window, document, $) {
    let orgType = [1000, 100, 10, 1]
    let index = 0, allOrgInfo
    $(function () {
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px'
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px'
        });
        _initData()
        _intitCommand()

    });
    const _initData = async () => {
        index = 0
        allOrgInfo = await SwitchOrgAPI.queryUserOrg()
        let curOrgId = defaultToken.curOrgId
        let curOrgName = defaultToken.curOrgName
        $('#nowOrg').text(curOrgName)
        let nowOrg = allOrgInfo.filter(item => item.oId == curOrgId)
        let parentArr = getAllParend(nowOrg[0]?.poId, allOrgInfo)
        let newparentArr = parentArr.reverse()
        let newArrs = [...newparentArr, ...nowOrg]
        removeRepeat(newArrs)
        if (Utils.IsNotNull(newArrs)) {
            for (let i = 0; i < newArrs.length; i++) {
                if (i == 0) {
                    let siblingArr = allOrgInfo.filter(item => item.poId == newArrs[i].poId)
                    _initOrg(siblingArr)
                }
                $(`#${newArrs[i].oId}`).click()
            }
        }
    }
    function removeRepeat(tempArr) {
        for (let i = 0; i < tempArr.length; i++) {
            for (let j = i + 1; j < tempArr.length; j++) {
                if (tempArr[i].aoType == tempArr[j].aoType && tempArr[i].poId != -1 && tempArr[j].poId != -1) {
                    tempArr.splice(i, 1);
                    j--;
                };
            };
        };
        return tempArr;
    };
    const _intitCommand = async () => {
        // 点击导航栏
        $('#selectOrg').on('click', 'li', function () {
            $(this).addClass('activeStyle').siblings('li').removeClass('activeStyle')
            $(this).find('.uderline').addClass('underlineit')
            $(this).siblings('li').find('.uderline').removeClass('underlineit')
            index = $(this).index()
            $('#orgContain').children('div').eq(index).show().siblings('div').hide()
        })
        // 确定
        $('#editOrg').on('click', function (e) {
            let selectId = $('.activeStyle:last').attr('id')
            let selectArr = allOrgInfo.filter(item => item.oId == selectId)
            let curOrgId = defaultToken.curOrgId
            if (selectId == curOrgId) {
                return $.toptip('切换的组织和当前组织一致，请选择其他组织', 'warning');
            }
            if (selectArr[0].optTag == 0) {
                return $.toptip('没有当前组织权限，请选择其他组织', 'warning');
            }
            savetips()
        })

        $(document).on('click', '.orgContain div:not(.noorgclick) .orgItem', async function () {
            let addressid = $(this).attr('id')
            operateStyle($(this))
            let selfArr = allOrgInfo.filter(item => item.oId == addressid)
            let childArr
            if (selfArr[0]?.aoType <= 10) {
                childArr = getAllChild(selfArr[0]?.oId, allOrgInfo)
            }
            else {
                childArr = allOrgInfo.filter(item => item.poId == addressid)
            }
            _initOrg(childArr)

        })
        $(document).on('click', '.noorgclick .orgItem', async function () {
            operateStyle($(this))
        })
    }

    const _initOrg = async (orgInfo) => {
        $('#orgContain').children('div').eq(index).empty()
        $('#orgContain').children('div').eq(index).show().siblings('div').hide()
        orgInfo.forEach(item => {
            $('#orgContain').children('div').eq(index).append(`<div class="orgItem ${item.oId}" id="${item.oId}" >${item.oName}</div>`)
        })
    }

    // 样式
    const operateStyle = (that) => {
        let addressName = that.text()
        that.siblings('div').find('i').remove()
        that.append(`<i class="icon iconfont icon-snh6-gou icon-font-size-24 selgou"
            aria-hidden="true"></i>`)

        that.addClass('activeStyle').parent().nextAll('div').find('div').removeClass('activeStyle')
        that.addClass('activeStyle').siblings('div').removeClass('activeStyle')
        $('#selectOrg').find('li').eq(index).find('span').text(addressName)
        index = index + 1
        changeStyle(index)
    }

    const changeStyle = (id) => {
        $('#selectOrg').find('li').eq(id).find('span').text('请选择')
        $('#selectOrg').find('li').eq(id).nextAll().find('span').text('')
        $('#selectOrg').find('li').eq(id).addClass('activeStyle').siblings('li').removeClass('activeStyle')
        $('#selectOrg').find('li').eq(id).find('.uderline').addClass('underlineit')
        $('#selectOrg').find('li').eq(id).siblings('li').find('.uderline').removeClass('underlineit')
    }
    // 保存提示
    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '确认切换',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;">
                        <div class="addentry" style="text-align: left;">
                            当前为【<span style="color:red">${defaultToken.curOrgName}</span>】组织，是否确认换成【<span style="color:red">${$('.activeStyle:last').text()}</span>】组织？
                        </div>
                    </div> 
                  </div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "确认", onClick: function () {
                        $.closeModal();
                        let selectId = $('.activeStyle:last').attr('id')
                        let switchJson = {
                            "ouId": selectId,
                            "cip": Utils.GetSessionStorage("CIP")
                        }
                        SwitchOrgAPI.switchOrg(switchJson).then(async res => {
                            var SNAuthAT = Utils.GetSessionStorage('SNAuthAT');
                            if (SNAuthAT != null) {
                                await Utils.SetSessionStorage("SNAuthAT", res.accessToken)
                                SwitchOrgAPI.queryUserName().then(res => {
                                    Utils.SetSessionStorage("SNLoginUserInfo", res);
                                })
                                $.toptip('切换成功', 'success');
                                location.href = `../../../../html/features/main.html`
                            }
                        })
                    }
                }
            ]
        });
    }

    // 递归获取选中系统的父级
    const getAllParend = (id, data) => {//这里的id为子数据的pid，不要混淆了
        var res = []; //定义一个数组用来存放找到的所有父级
        function dg(p) {
            for (var i = 0; i < data.length; i++) {
                var obj = data[i];
                if (obj.oId == p) {
                    res.push(obj); //将找到的父级元素放到res中
                    dg(obj.poId);
                }
            }
        }
        dg(id);
        return res;//返回找到的数据
    }
    // 递归获取选中系统的子级
    const getAllChild = (id, data) => {
        var res = [];
        function dg(p) {
            for (var i = 0; i < data.length; i++) {
                var obj = data[i];
                if (obj.poId == p) {
                    res.push(obj);
                    dg(obj.oId);
                }
            }
        }
        dg(id);
        return res;
    }
})(window, document, jQuery)